package org.yanghe.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.List;

@RestController
public class ConsumerController {

    @Value("${spring.application.name}")
    private String currentServiceName; //当前服务名
    @Resource
    RestTemplate restTemplate;
    @Resource
    DiscoveryClient discoveryClient;


    /**
     * 测试接口
     * @param name
     * @return
     */
    @GetMapping("/consumer/hello/{name}")
    public String hello(@PathVariable("name") String name){
        List<String> services = getServices(); //获取服务列表
        if(services.size()>0){
            for (String service : services) {
                if(!service.equals(currentServiceName)){ //排除自身服务
                    return restTemplate.getForObject("http://"+service+"/provider/hello/"+name,String.class);
                }
            }
        }
        return "Not Found";
    }


    /**
     * 获取服务列表
     * @return
     */
    @RequestMapping("/consumer/getServices")
    public List<String> getServices(){
        return discoveryClient.getServices();
    }
}

